package com.mine.modules.sys.service.impl;

import com.mine.common.constant.CommonConstant;
import com.mine.common.domain.vo.Result;
import com.mine.common.utils.SqlInjectionUtil;
import com.mine.modules.sys.common.utils.ResourceUtil;
import com.mine.modules.sys.domain.vo.DictModel;
import com.mine.modules.sys.domain.vo.DictModelMany;
import com.mine.modules.sys.entity.SysDict;
import com.mine.modules.sys.entity.SysDictItem;
import com.mine.modules.sys.mapper.SysDictMapper;
import com.mine.modules.sys.service.ISysDictItemService;
import com.mine.modules.sys.service.ISysDictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-09
 */
@Service
@RequiredArgsConstructor
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements ISysDictService {

    private final ISysDictItemService sysDictItemService;

    private final SysDictMapper sysDictMapper;

    @Override
    public Result<?> getDictByCode(String code) {
        SysDict sysdict = lambdaQuery().eq(SysDict::getDictCode, code).one();
        if (sysdict == null) {
            return Result.error("未找到数据字典！");
        }
        return Result.ok(sysDictItemService.lambdaQuery().eq(SysDictItem::getDictId, sysdict.getId()).orderByAsc(SysDictItem::getSortOrder).list());
    }

    @Override
    public List<DictModel> queryTableDictTextByKeys(String table, String text, String code, List<String> keys) {
        String filterSql = null;
        if(table.toLowerCase().indexOf(CommonConstant.SQL_WHERE)>0){
            String[] arr = table.split(" (?i)where ");
            table = arr[0];
            filterSql = arr[1];
        }
        String[] tableAndFields = new String[]{table, text, code};
        SqlInjectionUtil.filterContent(tableAndFields);
        SqlInjectionUtil.specialFilterContentForDictSql(filterSql);
        return sysDictMapper.queryTableDictByKeysAndFilterSql(table, text, code, filterSql, keys);
    }

    @Override
    public Map<String, List<DictModel>> queryManyDictByKeys(List<String> dictCodeList, List<String> keys) {
        List<DictModelMany> list = sysDictMapper.queryManyDictByKeys(dictCodeList, keys);
        Map<String, List<DictModel>> dictMap = new HashMap(5);
        for (DictModelMany dict : list) {
            List<DictModel> dictItemList = dictMap.computeIfAbsent(dict.getDictCode(), i -> new ArrayList<>());
            dictItemList.add(new DictModel(dict.getValue(), dict.getText()));
        }
        Map<String, List<DictModel>> enumRes = ResourceUtil.queryManyDictByKeys(dictCodeList, keys);
        dictMap.putAll(enumRes);
        return dictMap;
    }

}
